import { useState } from 'react'
import { Button, Form, Input, message } from 'antd'
import styles from './index.module.less'
import api from '@/api'
import { Login } from '@/types/api'
import storage from '@/utils/storage'
import { useStore } from '@/store'
export default function LoginFC() {
  const [loading, setLoading] = useState(false)
  const updateToken = useStore(state => state.updateToken) // 更新token
  const onFinish = async (values: Login.params) => {
    try {
      setLoading(true)
      const data = await api.login(values)
      setLoading(false)
      storage.set('token', data)
      updateToken(data) // 更新token
      message.success('登录成功')
      // 当登陆人退出后再次登录可以直接返回到 退出时的页面
      // location.search ?callback = xxx
      // URLSearchParams 可获取到 xxx
      const params = new URLSearchParams(location.search) // ****
      console.log('location.search', location.search)
      console.log('params', params)
      // 欢迎页或者之前退出的页面
      setTimeout(() => {
        location.href = params.get('callback') || '/welcome'
      })
    } catch (error) {
      setLoading(false)
    }
  }
  return (
    <div className={styles.login}>
      <div className={styles.loginWrapper}>
        <div className={styles.title}>系统登录</div>
        {/*
					name 命名
					initialValues 初始化值设置
					emember true，页面加载时，表单的"记住我"复选框会被勾选
					autoComplete='off': 浏览器不会自动填充表单字段内容。
				*/}
        <Form name='basic' initialValues={{ remember: true }} onFinish={onFinish} autoComplete='off'>
          <Form.Item name='userName' rules={[{ required: true, message: '请输入账号' }]}>
            <Input />
          </Form.Item>
          <Form.Item name='userPwd' rules={[{ required: true, message: '请输入密码' }]}>
            <Input.Password />
          </Form.Item>
          <Form.Item>
            <Button type='primary' block htmlType='submit' loading={loading}>
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}
